package idv.jieh.commons.util;

import java.io.*;
import java.util.Properties;
import java.net.URL;
/**
 * <p>Title: 藍色小惡魔的系統</p>
 *
 * <p>Description: 為別人做牛做馬好幾年了，總是要弄點自己的東西才有意思，你說是吧！</p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: BlueImp</p>
 *
 * @author Jieh
 * @version 1.0
 */
public class MyProperties extends Properties {
  private String header = "BlueImp Commons Properties File";

  public MyProperties(String filename) throws IOException {
    File file = createFile(filename);
    FileInputStream is = new FileInputStream(file);
    load(is);
    is.close();
  }

  /**
   * 儲存設定檔。<p>
   * @param filename 檔案名稱。
   */
  public void store(String filename) {
    try {
      File file = createFile(filename);
      java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
      store(fos, header);
      fos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 設定回存時的 header。<p>
   * @param s header 內容。
   */
  public void setHeader(String s) {
    header = s;
  }

  /**
   * 開啟一個 File 物件並回傳。<p>
   * 2005-02-25 add by jieh <br>
   * 這個方法會試圖到 JVM class 路徑 中找到指定的檔案，如果檔案不存在，將會自動建立一個
   * 新的檔案。
   * @param filename 檔案名稱。
   * @return File
   * @throws IOException
   */
  private File createFile(String filename) throws IOException {
    String fullpath = getClass().getResource("/").getFile() + filename;

    getClass().getResourceAsStream(filename);

//    System.out.println(". ==> "+ getClass().getResourceAsStream(filename));
//    System.out.println(". ==> "+ getClass().getResource(filename).getPath());

    fullpath = DataAnalysis.replace(fullpath, "%20", " ");
    File file = new java.io.File(fullpath);
    if (!file.exists()) {
      System.out.println(filename + " Config File is't exist...");
      if (file.createNewFile()) {
        System.out.println(fullpath + " Config file created success!!! ");
      }
    }
    return file;
  }

  public static void main(String... args) throws Exception{
    MyProperties me = new MyProperties("jieh-test.properties");
  }
}
